<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of PHP-MELANGE.
 *
 * PHP-MELANGE is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-MELANGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-MELANGE; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    Melange
 * @package     php-melange
 * @subpackage  cms
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 *
 */

require_once("cms/core/action/AbstractListAction.php");

class ListAction extends AbstractListAction {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("ListAction");
    }

    public function activate(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Activating contents");
        
        // Add only deactivated content to search engine.        
        if($request->getContext()->getInitParameter(_Core::SEARCH) === true) {
            $c = new Criteria();
            $c->add(ContentI18nPeer::ACTIVE, false);
            $c->add(ContentI18nPeer::CONTENT_I18N_ID, $form->getItems(), Criteria::IN);
            $contentI18ns = ContentI18nPeer::doSelect($c);
            foreach($contentI18ns as $contentI18n) {
            	$contentI18n->addToIndex($request->getContext()->
                    getInitParameter(_Core::SEARCH_INDEX_PATH));
            }
        }
        
        // Update database
        $c = new Criteria();
        $c->add(ContentI18nPeer::CONTENT_I18N_ID, $form->getItems(), Criteria::IN);
        $c->add(ContentI18nPeer::ACTIVE, true);
        try {
            ContentI18nPeer::doUpdate($c);
            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.activate", true));
                
            if($request->getContext()->getInitParameter(_Core::CACHE)) {
                // Get the cache
                $cache = $request->getContext()->getCache();
                // Clear the menu cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));             
                // Clear the page cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
            }
                
        } catch(PropelException $e) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.activate", true));
            $this->log->error($e->getMessage());
        }

    }

    public function deactivate(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Deactivating contents");
        $c = new Criteria();
        $c->add(ContentI18nPeer::CONTENT_I18N_ID, $form->getItems(), Criteria::IN);
        $c->add(ContentI18nPeer::ACTIVE, false);
        try {
            ContentI18nPeer::doUpdate($c);
            
            // Delete content from search index
            if($request->getContext()->getInitParameter(_Core::SEARCH) === true) {
                require_once("util/Search.php");
                $search = new Search($request->getContext()->
                    getInitParameter(_Core::SEARCH_INDEX_PATH));
                // Delete entries from search index
                foreach ($form->getItems() as $contentI18nId) {
            	    $search->remove("content_".$contentI18nId);
                }
            }            
            
            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.deactivate", true));
                
            if($request->getContext()->getInitParameter(_Core::CACHE)) {
                // Get the cache
                $cache = $request->getContext()->getCache();
                // Clear the menu cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));             
                // Clear the page cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
            }
                
        } catch(PropelException $e) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.deactivate", true));
            $this->log->error($e->getMessage());
        }

    }

    public function feature(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Featuring contents");

        $conn = Propel::getConnection();

        try {

            // Unfeature all first
            $c = new Criteria();
            $c->add(ContentI18nPeer::FEATURED, false);
            $c->add(ContentI18nPeer::CONTENT_I18N_ID, 0, Criteria::GREATER_THAN);
            ContentI18nPeer::doUpdate($c, $conn);

            // Feature 1st chosen
            $items = $form->getItems();
            $c = new Criteria();
            $c->add(ContentI18nPeer::CONTENT_I18N_ID, $items[0], Criteria::IN);
            $c->add(ContentI18nPeer::FEATURED, true);
            $c->setLimit(1);

            ContentI18nPeer::doUpdate($c, $conn);
            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.feature", true));
                
            if($request->getContext()->getInitParameter(_Core::CACHE)) {
                // Get the cache
                $cache = $request->getContext()->getCache();
                // Clear the menu cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));
                // Clear the page cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
            }

        } catch(PropelException $e) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.feature", true));
            $this->log->error($e->getMessage());
        }

    }

    public function unfeature(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Unfeaturing contents");
        $c = new Criteria();
        $c->add(ContentI18nPeer::CONTENT_I18N_ID, $form->getItems(), Criteria::IN);
        $c->add(ContentI18nPeer::FEATURED, false);
        try {
            ContentI18nPeer::doUpdate($c);
            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.deactivate", true));
                
            if($request->getContext()->getInitParameter(_Core::CACHE)) {
                // Get the cache
                $cache = $request->getContext()->getCache();
                // Clear the menu cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));             
                // Clear the page cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
            }
                
        } catch(PropelException $e) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.deactivate", true));
            $this->log->error($e->getMessage());
        }

    }

    public function delete(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $this->log->debug("Deleting contents");

        $c = new Criteria();
        $c->add(ContentI18nPeer::CONTENT_I18N_ID, $form->getItems(), Criteria::IN);

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            $contentI18ns = ContentI18nPeer::doSelect($c);
            foreach($contentI18ns as $contentI18n) {
            	
                // Delete the content itself
                if($contentI18n->getLanguageCode() ==
                        $request->getContext()->getInitParameter(_Core::DEFAULT_LANGUAGE)) {

                    $content = $contentI18n->getContent();

                    // Move all higher positions one up.
                    $query =
                    "UPDATE content SET position = position - 1 ".
                    "WHERE category_id = " .$content->getCategoryId()." ".
                    "AND position > " . $content->getPosition();

                    $stmt = $conn->createStatement();
                    $stmt->executeUpdate($query, $conn);
                    
                    // Delete this content's i18ns from the index
                    if($request->getContext()->getInitParameter(_Core::SEARCH) === true) {
                        
                        require_once("util/Search.php");
                        
                        $search = new Search($request->getContext()->
                            getInitParameter(_Core::SEARCH_INDEX_PATH));
                    
                        // Get this content i18ns and remove them from search index
                        $query = "SELECT content_i18n_id FROM content_i18n ".
                                 "WHERE active=1 AND content_id = " . $content->getContentId();

                        $rs = $stmt->executeQuery($query, ResultSet::FETCHMODE_NUM);
                    
                        // Delete entries from search index
                        while($rs->next()) {
                            $search->remove("content_".$rs->getString(1));
                        }
                        
                    }

                    // Delete the Content and have the onDelete=cascade take care of the rest.
                    ContentPeer::doDelete($contentI18n->getContentId(), $conn);

                } else {
                	
                    // Delete just this i18n from the index
                    if($request->getContext()->getInitParameter(_Core::SEARCH) === true) {
                        require_once("util/Search.php");
                        $search->remove("content_".$contentI18n->getContentI18nId());
                    }
                	
                    // Just this row.
                    ContentI18nPeer::doDelete($contentI18n->getContentI18nId(), $conn);
                }
            }

            $this->messages->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.success.delete", true));
                
            if($request->getContext()->getInitParameter(_Core::CACHE)) {
                // Get the cache
                $cache = $request->getContext()->getCache();
                // Clear the menu cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));             
                // Clear the page cache
                $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
            }    

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.delete", true));
            $this->log->error($e);
        }

    }

    public function moveup(ActionConfig &$mapping, &$form, Request &$request,
            Response &$response) {
        $this->move($form, "up", $request);
    }

    public function movedown(ActionConfig &$mapping, &$form, Request &$request,
            Response &$response) {
        $this->move($form, "down", $request);
    }

    private function move($form, $direction, Request &$request) {

        $items = $form->getItems();

        $contentI18n = ContentI18nPeer::retrieveByPk($items[0]);
        $content = $contentI18n->getContent();

        if(is_null($content)) {
            $this->errors->add(ActionMessage::GLOBAL_MESSAGE, new ActionMessage("Error finding content."));
            return;
        }

        $conn = Propel::getConnection();
        $stmt = $conn->createStatement();

        try {

            $conn->begin();

            $query =
                "UPDATE content SET position = position ".($direction == "down" ? "-" : "+")." 1 ".
                "WHERE ".
                "category_id = ".$content->getCategoryId()." ".
                "AND position = ".($direction == "down" ? $content->getPosition() + 1 : $content->getPosition() - 1);

            $stmt->executeUpdate($query, $conn);

            $query =
                "UPDATE content SET position = position ".($direction == "down" ? "+" : "-")." 1 ".
                "WHERE ".
                "category_id = ".$content->getCategoryId()." ".
                "AND content_id = ".$content->getContentId();

            $stmt->executeUpdate($query, $conn);
            
            if($request->getContext()->getInitParameter(_Core::CACHE)) {
            	// Get the cache
	           $cache = $request->getContext()->getCache();
	           // Clear the menu cache
               $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));	            
    	       // Clear the page cache
	           $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("list.error.move", true));
            $this->log->error($e->getMessage());
        }

    }

}
?>